#include "screenshot.h"
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
using namespace std;

void grab(int width, int height) {
    FILE *pDummyFile;
    FILE *pWritingFile;
    GLubyte *pPixelData;
    GLubyte BMP_Header[BMP_Header_Length];
    GLint i, j;
    GLint PixelDataLength;

    time_t t = time(0);
    char filename[40];
    strftime(filename, sizeof(filename), "%Y%m%d%H%M%S", localtime(&t));
	int a = rand() % 9000 + 1000;
    char str[6];
    char filepath[100] = FilePathGrab;
    sprintf(str, "%d", a);
    strcat(filename, str);
    strcat(filename, ".bmp");
    strcat(filepath, filename);
    // cout << filepath << endl;

    i = width * 3;
    while (i % 4 != 0)
        ++i;
    PixelDataLength = i * width;

    pPixelData = (GLubyte *)malloc(PixelDataLength);
    if (pPixelData == 0)
        exit(0);

    pDummyFile = fopen(BMP_Header_path, "rb");
    if (pDummyFile == 0)
        exit(0);

    pWritingFile = fopen(filepath, "wb");
    if (pWritingFile == 0)
        exit(0);

    fread(BMP_Header, sizeof(BMP_Header), 1, pDummyFile);
    fwrite(BMP_Header, sizeof(BMP_Header), 1, pWritingFile);

    // fwrite(BMP_Header, sizeof(BMP_Header), 1, pWritingFile1);
    fseek(pWritingFile, 0x0012, SEEK_SET);
    i = width;
    j = height;
    fwrite(&i, sizeof(i), 1, pWritingFile);
    fwrite(&j, sizeof(j), 1, pWritingFile);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
    glReadPixels(0, 0, width, height, GL_BGR_EXT, GL_UNSIGNED_BYTE, pPixelData);

    fseek(pWritingFile, 0, SEEK_END);
    fwrite(pPixelData, PixelDataLength, 1, pWritingFile);

    fclose(pDummyFile);
    fclose(pWritingFile);
    free(pPixelData);
}
